package com.tacc.tyun.controller;

import com.tacc.tyun.base.BaseConstant;
import com.tacc.tyun.model.BaseDepart;
import com.tacc.tyun.model.BaseUser;
import com.tacc.tyun.model.info.BaseUserInfo;
import com.tacc.tyun.model.info.ReturnEntity;
import com.tacc.tyun.service.BaseDepartService;
import com.tacc.tyun.service.BaseUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录
 * @author taocongcong
 * @create 2017-07-14 17:00
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private BaseDepartService baseDepartService;

    @RequestMapping("/page")
    public ModelAndView toLoginPage(){
        ModelAndView mv=new ModelAndView("login");
        return mv;
    }

    @RequestMapping(value = "/ajaxLogin",method = RequestMethod.POST)
    @ResponseBody
    public ReturnEntity login(HttpServletRequest request, BaseUserInfo baseUserInfo){
        UsernamePasswordToken token = new UsernamePasswordToken(baseUserInfo.getUserid(), baseUserInfo.getUserpassword(),true);
        try {
            SecurityUtils.getSubject().login(token);

        } catch (DisabledAccountException  de){
            return new ReturnEntity(BaseConstant.CODE_ERROR,"由于密码输入错误次数大于3次，帐号已经禁止登录！");
        } catch (AccountException ae){
            return new ReturnEntity(BaseConstant.CODE_ERROR,"帐号或密码不正确！");
        }


        BaseUser baseUser=baseUserService.selectByPrimaryKey(baseUserInfo.getUserid());
        BaseDepart baseDepart=baseDepartService.selectByPrimaryKey(baseUser.getDepartid());
        baseUserInfo.setDepartid(baseUser.getDepartid());
        baseUserInfo.setUsername(baseUser.getUsername());
        baseUserInfo.setUserpassword(baseUser.getUserpassword());
        baseUserInfo.setBaseDepart(baseDepart);
        baseUserInfo.setHeadLogo(baseUser.getHeadlogo());
        request.getSession().setAttribute(BaseConstant.SESSION_USERINFO,baseUserInfo);
        //异常则表示未登录成功
        SecurityUtils.getSubject().getSession().setAttribute("yunyun","yunyun");
        return new ReturnEntity(BaseConstant.CODE_SUCCESS,baseUser,"/index");
    }
}
